import React, { Component } from 'react';
import { NavigationEvents } from 'react-navigation';
import {
	StyleSheet, Text, View, TouchableOpacity, TextInput, Alert,
	Image, PixelRatio, FlatList, Modal
} from "react-native";

import { API, API_GENERATE } from '../../../../config/api';
import HTTP from '../../../../utils/http';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common';
import ToastUtil from '../../../../utils/toast';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { ListItem } from '../../../enterprise/credit/judgement/_component/ListItem';
import { ProductEditing } from '../../highSeas/_components/ProductEditing';
const scale = GLOBAL.SCALE;

const searchIcon = require('../../../../imgs/global/whiteSearch.png');
const addIcon = require('../../../../imgs/customer/company-add.jpg');
const claimIcon = require('../../../../imgs/customer/renling.jpg');
const correct = require('../../../../imgs/global/correct.png');
const locked = require('../../../../imgs/customer/suoding.png');
const unLock = require('../../../../imgs/customer/zhengchang.png');

export class CustomerLossPage extends Component {
	constructor(props) {
		super(props);
		this.state = {
			status: 'data',
			listData: [],
			refreshIcon: false, // 下拉刷新图标
			approveCntInfo: {},
			goodsModal: false
		}

		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数

		this.pageParams = { // TODO
			searchKey: '',
			isEdit: null,
			pageNo: 1
		}
	}
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '客户列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.navigate('CrMtManage') }} color='#fff' />,
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	//初始化数据
	async componentDidMount() {
		await this.initPage();
	}

	componentWillUnmount() {
		this.pageParams.pageNo = 1;
	}

	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let res = await HTTP.POST(API_GENERATE(API.GET_LOSS_LIST), this.pageParams); // TODO
		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
				curTypeCnt: res.recordCount || 0
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	reloadPage() {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 下拉刷新
	refresh() {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.initPage();
	}

	// 上拉翻页
	loadMore() {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	async	_getGoodsLossList(companyId) {
		let res = await HTTP.POST(API_GENERATE(API.GET_GOODS_LOSS_LIST), { companyId }); // TODO
		this.setState({
			companyGoodsTreeList: res
		})
	}

	_cancelPress(a) {
		this.setState({ goodsModal: false })
	}
	// 搜索View
	_renderFilterWrap() {
		return (
			<View style={styles.filterWrap}>
				<View>
					<Image source={searchIcon} style={styles.searchIcon} />
					<TextInput
						ref="enterpriseInput"
						style={styles.searchInput}
						underlineColorAndroid='transparent'
						placeholder={"请输入企业名称"}
						placeholderTextColor="rgba(255, 255, 255, .8)"
						maxLength={30}
						returnKeyType={'search'}
						defaultValue={this.pageParams.searchKey}
						onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
						onSubmitEditing={() => { this.reloadPage(true); }}
					/>
				</View>
			</View>
		)
	}

	_renderListItem = (data) => {
		const { companyId, companyName, isFrozen } = data.item;
		return (
			<TouchableOpacity style={styles.listItem} key={data.index} >
				<View style={styles.listItemInfo}>
					<Text style={styles.companyNameText}>{companyName.length > 14 ? `${companyName.substring(0, 14)}...` : companyName}</Text>
					<TouchableOpacity style={styles.listItemRightInfo} activeOpacity={1}>
						<Image source={isFrozen ? locked : unLock} style={{ width: 15 * scale, height: 15 * scale }} />
					</TouchableOpacity>
				</View>
				<Text style={styles.checkLossGoods} onPress={() => { this.setState({ goodsModal: true }, () => { this._getGoodsLossList(companyId) }) }}>【查看即将流失产品】</Text>
			</TouchableOpacity>
		)

	}

	render() {
		const { status, listData, refreshIcon, goodsModal, companyGoodsTreeList } = this.state;
		const { choice } = this.props.navigation.state.params;
		return (
			<View style={styles.container}>
				<View style={styles.accountInfo}>
					<Text style={styles.accountText}>业务组织：{choice.corpName}</Text>
				</View>
				{this._renderFilterWrap()}
				{
					status == 'data' ? (
						<View style={{ flex: 1, backgroundColor: '#FFF' }}>
							<FlatList
								data={listData}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View>) : null
				}
				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={() => { this.reloadPage() }} />) : null
				}

				<Modal animationType={"fade"}
					transparent={true}
					onRequestClose={() => { console.log(1) }}
					visible={goodsModal}>
					<View style={styles.back}>
						<TouchableOpacity activeOpacity={1} style={styles.bg} onPress={() => { this._cancelPress() }}>
						</TouchableOpacity>
						{/**企业经营品类 */}
						<ProductEditing
							data={companyGoodsTreeList || []}
							visible={true}
							widthoutTop={true}
							showLossInfo={true} />
					</View>
				</Modal>
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	filterWrap: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: style.color.themeColor,
		paddingTop: 14 * scale,
		paddingBottom: 14 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: 260 * scale,
		paddingLeft: 60 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
	},
	searchIcon: {
		width: 20 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 24 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	listItem: {
		borderBottomWidth: 1 * scale,
		borderBottomColor: '#D8D8D8',
		paddingTop: 22 * scale,
		paddingBottom: 8 * scale,
	},
	listItemInfo: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		marginLeft: 24 * scale,
		marginRight: 28 * scale,
		marginBottom: 14 * scale,
	},
	listItemRightInfo: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center'
	},
	companyNameText: {
		fontSize: 14 * scale,
		color: '#000',
		fontWeight: '700',
		marginLeft: 8 * scale
	},
	checkLossGoods: {
		color: style.color.themeColor,
		fontSize: 10 * scale,
		marginLeft: 28 * scale
	},
	back: {
		width: 375 * scale,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		height: GLOBAL.SCREEN_HEIGHT,
	},
	bg: {
		width: 375 * scale,
		height: '20%',
	},
	accountInfo: {
		flexDirection: 'row',
		justifyContent: 'flex-end',
		backgroundColor: style.color.themeColor,
		height: 30 * scale,
		paddingTop: 5 * scale,
		paddingRight: 12 * scale
	},
	accountText: {
		fontWeight: '600',
		color: '#fff'
	}
})